$(document).ready(function(){                    
    var canvas = document.getElementById('canvas');
    var stage = new JTopo.Stage(canvas);
    stage.frames = 0;
    //显示工具栏
    showJTopoToobar(stage);
    var scene = new JTopo.Scene();
    stage.showToolbar = false;
    scene.shadow = true;
    scene.backgroundColor = '0,0,0';
    scene.alpha = 1;
    stage.add(scene);
    
    var nodes = [];
    
    function create_node(){
        var x = Math.random() * stage.width;
        var y = Math.random() * stage.height;
        var node = new JTopo.CircleNode();
        node.vx = Math.random() * 6 - 3;
        node.vy = Math.random() * 6 - 3;
        node.radius = Math.random() * 10 + 2;
        node.mass = node.radius;
        node.fillColor = JTopo.util.randomColor();
        node.setLocation(x, y);
        scene.add(node);
        return node;
    }
    
    for(var i=0; i<90; i++){
        var node = create_node();
        nodes.push(node);
    }
    function move(node){
        node.x += node.vx;
        node.y += node.vy;
        if(node.x > stage.width){
            node.x = 0;
        }
        if(node.y> stage.height){
            node.y = 0;
        }
        if(node.x - node.width < 0){
            node.x = stage.width;
        }
        if(node.y - node.height < 0){
            node.y = stage.height;
        }
    }
    
    var minDist = 100;
    var springAmount = 0.0025;
    function spring(a, b){
        var dx = b.x - a.x;
        var dy = b.y - a.y;
        var dist = JTopo.util.getDistance(a, b);
        
        if(dist < minDist){
            var g = stage.graphics;
            var alpha = 1 - dist / minDist;
            g.beginPath();
            g.strokeStyle = 'rgba(255,255,255,'+alpha+')';
            g.lineWidth = 1;
            g.moveTo(a.x + a.width/2, a.y + a.height/2);
            g.lineTo(b.x + b.width/2, b.y + b.height/2);
            g.stroke();
            g.closePath();
            var ax = dx * springAmount;
            var ay = dy * springAmount;
            a.x += ax / a.mass;
            a.y += ay / a.mass;
            b.x -= ax / b.mass;
            b.y -= ay / b.mass;
        }
    }
    (function f(){
        stage.paint();
        for(var i=0; i<nodes.length; i++){
            for(var j=0; j<nodes.length; j++){
                if(j == i) continue;
                spring(nodes[i], nodes[j]);
            }
            move(nodes[i]);
        }
        
        requestAnimationFrame(f);
    })();
    
    stage.addEventListener('mouseup', function(e){
        var node = create_node();
        node.setLocation(e.x, e.y);
        nodes.push(node);
    });
});